﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace STAR.Spring.Framework
{
    public static class PagedHelper
    {
        public static dynamic GetPagedData<T>(this List<T> allData)
        {
            int pageNum = 1;
            int pageSize = 10;

            #region 获取分页参数
            string pNString = HttpContext.Current.Request["PN"];
            string pSString = HttpContext.Current.Request["PS"];

            if (!string.IsNullOrEmpty(pNString))
            {
                int.TryParse(pNString, out pageNum);
                if (pageNum < 1)
                {
                    pageNum = 1;
                }

            }
            if (!string.IsNullOrEmpty(pSString))
            {
                int.TryParse(pSString, out pageSize);
                if (pageSize < 1)
                {
                    pageSize = 10;
                }
            }
            int total = allData.Count;
            int maxPageNum = total / pageSize + 1;
            if (pageNum > maxPageNum)
            {
                pageNum = maxPageNum;
            }
            #endregion

            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = pageNum * pageSize;
            endIndex = endIndex > total ? total : endIndex;

            int returnCount = endIndex - startIndex;

            List<T> pagedInfos = allData.Skip(startIndex).Take(returnCount).ToList();
            return new
            {
                Total = total,
                Num=pageNum,
                Size=pageSize,
                Data = pagedInfos
            };
        }
    }
}